import { AppError } from "common";
import type Application from "koa";
import { ZodError } from "zod";

const errorHandlingMiddleware: Application.Middleware = async (ctx, next) => {
  try {
    await next();
  } catch (e) {
    console.error("error: ", e);
    if (e instanceof AppError) {
      ctx.status = e.code;
      ctx.body = { code: e.code, message: e.message };
      return;
    }
    if (e instanceof ZodError) {
      ctx.status = 400;
      ctx.body = { code: 400, message: e.errors[0]?.message };
      return;
    }
    if (e instanceof Error) {
      ctx.status = 500;
      ctx.body = { code: 500, message: "Internal server error" };
      return;
    }
    ctx.status = 500;
    ctx.body = { code: 500, message: "Internal server error" };
  }
};

export default errorHandlingMiddleware;
